package com.zyj.websocket;

import com.zyj.websocket2.EndpointHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@RestController
public class TestController {

    @Autowired
    private EndpointHandler endpoint2;

    private static String largeStr = "";

    static {
        StringBuilder sb = new StringBuilder();
//        for (int i = 0; i < 1000000; i++) {
        for (int i = 0; i < 10000; i++) {
            sb.append("222222222222222222");
        }
        largeStr = sb.toString();
    }

    private static final Executor EXECUTOR = Executors.newCachedThreadPool();

    @RequestMapping("broadcast")
    public void broadcast(@RequestParam("msg") String msg) {
        System.out.println("largeStr.length() = " + largeStr.length());
        for (int i = 0; i < 10000; i++) {
            //尝试并发广播大消息
            EXECUTOR.execute(() -> {
                try {
                    WebSocketServer.broadcast(largeStr);
                    endpoint2.broadcast(largeStr);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

}
